package com.cn.wanxi.util;


import java.sql.*;

public class JDBC {
    //    1.加载驱动
//    2.得到链接
//    3.编译sql语句
    static {
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    private JDBC() {
    }

//    private static Connection connection = null;

    private static Connection getConnection() {
        Connection connection=null;
//
//        String url = "jdbc:mysql://localhost:3306/你的数据库名称?serverTimezone=UTC";
//        String user = "你的数据库用户名root";
//        String pass = "你的数据库密码123456";
        String url = "jdbc:mysql://121.199.55.96:3306/canyin04";
        String user = "canyin04";
        String pass = "123456";
        if (connection == null) {
            synchronized (JDBC.class) {
                if (connection == null) {
                    try {
                        connection = DriverManager.getConnection(url, user, pass);
                    } catch (SQLException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
        return connection;
    }

    public static ResultSet query(String sql) {
//        getConnection();
        try {
//            编译sql语句
            PreparedStatement preparedStatement = getConnection().prepareStatement(sql);

            ResultSet resultSet = preparedStatement.executeQuery();
//            解析结果ResultSet集
            return resultSet;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }


    /**
     * 增加，删除，修改
     * @param sql
     * @return
     */
    public static int update(String sql) {
        try {
//            编译sql语句
            PreparedStatement preparedStatement = getConnection().prepareStatement(sql);
//            返回的时影响的条数
            return preparedStatement.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return 0;
    }


}
